import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, ToastController } from 'ionic-angular';
import {
  Http,
  Headers,
  RequestOptions,
  URLSearchParams
}from '@angular/http';
import { LoginPage } from '../login/login';
import { AppConfig } from '../../app/app.config';
import { Md5 } from "ts-md5/dist/md5";
import { baseCommon } from '../../common/baseCommon'
/**
 * Generated class for the Find2Page page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-find2',
  templateUrl: 'find2.html',
})
export class Find2Page{

  code:any;
  getPhone:any;
  password:any;
  passwordAgain:any;
  

  constructor(public navCtrl: NavController, public navParams: NavParams,public http: Http,public toastCtrl: ToastController) {
    this.getPhone = navParams.data.phone;
  }

  ionViewDidLoad() {
    // console.log('ionViewDidLoad Find2Page');
  }

  /**
   * 返回登录
   * 
   * @memberof Find2Page
   */
  login(){
    this.navCtrl.push(LoginPage);
  }

  /**
   * 找回密码
   * 
   * @memberof Find2Page
   */
  find(){
    if(this.code == ''){
      baseCommon.showToast(this.toastCtrl,'请输入验证码..');
    }else if(this.password == ''){
      baseCommon.showToast(this.toastCtrl,'请输入密码..');
    }else if(this.password != this.passwordAgain){
      baseCommon.showToast(this.toastCtrl, "两次输入的密码不一致！");
    }else if(this.password == this.passwordAgain) {
      this.Fing(AppConfig.httpLoc+'/reset/check',this.code,this.password,this.getPhone);
    } else{
      baseCommon.showToast(this.toastCtrl, "本程序猿也不知道发生了什么错误..");
    }
  }

  /**
   * 请求找回密码
   * 
   * @param {any} apiUrl 
   * @param {any} code 
   * @param {any} password 
   * @param {any} phone 
   * @memberof Find2Page
   */
  Fing(apiUrl,code,password,phone){
    let headers = new Headers({
      'Content-Type': 'application/x-www-form-urlencoded'
    });

    let options = new RequestOptions({
      headers: headers
    });

    let pramas :URLSearchParams = new URLSearchParams();

    pramas.set('code',code);
    pramas.set('password',Md5.hashStr(password).toString());
    pramas.set('phone',phone);

    let getData:any;

    this.http.post(apiUrl, pramas, options)
      .toPromise()
      .then( data => {
        getData = data.json();
        if(getData.message == "成功"){
          this.navCtrl.push(LoginPage);
        }else{
        }
      }, err => {
        console.log( err );
      })
  }
}
